package com.ruoyi.accountant.service.impl;

import com.ruoyi.accountant.dao.ReasonDao;
import com.ruoyi.accountant.domain.Reason;
import com.ruoyi.accountant.domain.ReasonExample;
import com.ruoyi.accountant.domain.SettingExample;
import com.ruoyi.accountant.mapper.ReasonMapper;
import com.ruoyi.accountant.service.ReasonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class ReasonServiceImpl implements ReasonService {
    //@Autowired
//    private ReasonDao reasonDao;

    @Autowired
    private ReasonMapper reasonMapper;

    public void save(Reason reson) {
        reson.setCreatetime(new Timestamp(System.currentTimeMillis()));
        reasonMapper.insert(reson);
    }

    @Override
    public List<Reason> findAll() {
        return reasonMapper.selectByExample(null);
    }

    @Override
    public void update(Reason reason) {
        reasonMapper.updateByPrimaryKeySelective(reason);
    }

    @Override
    public Reason findById(Long rid) {
        return reasonMapper.selectByPrimaryKey(rid);
    }

    @Override
    public void deleteById(Long rid) {
        Reason reason = reasonMapper.selectByPrimaryKey(rid);
        if(!reason.getRname().equals("設備折舊")) {
            // 查询子项目
            List<Reason> children = reasonMapper.findAllByParent(rid);
            for (Reason child : children) {
                deleteById(child.getRid());
            }
            reasonMapper.deleteByPrimaryKey(rid);
        }
    }

    @Override
    public List<Reason> findAllByParent(Long parentId) {
        ReasonExample reasonExample = new ReasonExample();
        reasonExample.createCriteria().andParentEqualTo(parentId);
        return reasonMapper.selectByExample(reasonExample);
    }

    @Override
    public Reason findByRname(String reasonName) {
        return reasonMapper.findByRname(reasonName);
    }

    @Override
    public List<Reason> findAllByLevel(int level) {
        return reasonMapper.findAllByLevel(level);
    }
}
